<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible=true">
          创建学习任务
        </el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="归属" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%" border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key" @sort-change="tableSortCge">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="150" align="center" prop="send_type" label="任务对象">
        <template slot-scope="scope">
          <span v-if="scope.row.send_type===1">按责任老师</span>
          <span v-else-if="scope.row.send_type===2">按账号</span>
          <span v-else-if="scope.row.send_type===3">按督学室</span>
          <span v-else>按伴学室</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="150" align="center" prop="sendName" label="对象选择">
        <template slot-scope="scope">
          <p v-for="item in scope.row.sendName">{{ item.name }}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="90" align="center" prop="date_type" label="任务类别">
        <template slot-scope="scope">
          <span v-if="scope.row.date_type===1">天任务</span>
          <span v-else-if="scope.row.date_type===2">周任务</span>
          <span v-else>月任务</span>
        </template>
      </el-table-column>

      <el-table-column v-if="colData[4].istrue" min-width="100" align="center" prop="subjectName" label="学科">
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="100" align="center" prop="name" label="任务名称"></el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="100" align="center" prop="remark" label="任务描述"></el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="140" align="center" label="是否提醒">
        <template slot-scope="scope">
          <span v-if="scope.row.is_remind===-1">否</span>
          <span v-else>{{ scope.row.remind_time }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[8].istrue" min-width="100" align="center" prop="adminName" label="归属"></el-table-column>
      <el-table-column label="操作" min-width="180" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="delContent(scope.row.id)">删除</el-button>
            <el-button size="mini" @click="showTaskDetail(scope.row.id)">查看</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText"/>

    <el-dialog :title="editSubjects ? '编辑' : '添加'" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="35%" @close="addFormclose">
      <el-form :model="addForm" ref="ruleForm" :rules="rules">
        <el-form-item label="学科:" label-width="130px" prop="subject">
          <el-select v-model="addForm.subject" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称:" label-width="130px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入任务名称" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="跳转方式:" label-width="130px" prop="jump_type">
          <el-select v-model="addForm.jump_type" placeholder="请选择">
            <el-option v-for="item in configOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转应用:" label-width="130px" prop="app_charge_id" v-show="addForm.jump_type===1">
          <el-select v-model="addForm.app_charge_id" placeholder="请选择">
            <el-option
              v-for="item in appChargeOptions"
              :key="item.app_id"
              :label="item.column_name"
              :value="item.app_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转网址:" label-width="130px" prop="app_charge_id" v-show="addForm.jump_type===5">
          <el-select v-model="addForm.link_url" placeholder="请选择">
            <el-option
              v-for="item in whiteUrlOption"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务对象:" label-width="130px" prop="send_type">
          <el-select v-model="addForm.send_type" @change="getSendOptions">
            <el-option :value="1" label="按责任老师"></el-option>
            <el-option :value="2" label="按账号"></el-option>
            <el-option :value="3" label="按督学室"></el-option>
            <el-option :value="4" label="按伴学室"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对象选择:" label-width="130px" prop="send_id">
          <el-select v-model="addForm.send_id" multiple filterable reserve-keyword placeholder="请输入关键词">
            <el-option
              v-for="item in sendOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务类别:" label-width="130px" prop="date_type">
          <el-select v-model="addForm.date_type" placeholder="请选择" :disabled="editSubjects">
            <el-option :value="1" label="天任务"></el-option>
            <el-option :value="2" label="周任务"></el-option>
            <el-option :value="3" label="月任务"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日选择:" label-width="130px" v-if="addForm.date_type===1" prop="date_select">
          <el-select v-model="addForm.date_select" placeholder="请选择" multiple>
            <el-option :value="1" label="周一"></el-option>
            <el-option :value="2" label="周二"></el-option>
            <el-option :value="3" label="周三"></el-option>
            <el-option :value="4" label="周四"></el-option>
            <el-option :value="5" label="周五"></el-option>
            <el-option :value="6" label="周六"></el-option>
            <el-option :value="7" label="周日"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="月份:" label-width="130px" prop="date_select" v-else-if="addForm.date_type===3">
          <el-date-picker
            type="months"
            v-model="addForm.date_select"
            value-format="yyyy-MM"
            placeholder="选择一个或多个月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期:" label-width="130px" v-if="addForm.date_type===1 || addForm.date_type===2">
          <el-date-picker
            v-model="addForm.expire_time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否提醒:" label-width="130px" prop="is_remind">
          <el-radio-group v-model="addForm.is_remind">
            <el-radio :label="1">提醒</el-radio>
            <el-radio :label="-1">不提醒</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提醒时间:" label-width="130px" v-show="addForm.is_remind===1" prop="remind_time">
          <el-time-picker
            v-model="addForm.remind_time"
            placeholder="请选择提醒时间"
            value-format="HH:mm"
            format="HH:mm">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="任务描述:" label-width="130px" prop="remark">
          <el-input type="textarea" v-model="addForm.remark" maxlength="120"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" @click="editStudentTaskControl('ruleForm')" size="mini" round>确定
        </el-button>
        <el-button v-else type="primary" @click="addStudentTaskControl('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="taskDetailVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务类别" :contentStyle="{'text-align': 'left'}">{{ taskInfo.dateExplain }}
        </el-descriptions-item>
        <el-descriptions-item label="有效期">{{ taskInfo.expireExplain }}</el-descriptions-item>
        <el-descriptions-item label="跳转方式">{{ taskInfo.jumpExplain }}</el-descriptions-item>
        <el-descriptions-item label="提醒时间">{{ taskInfo.remindExplain }}</el-descriptions-item>
        <el-descriptions-item label="责任老师">{{ taskInfo.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ taskInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="任务内容">{{ taskInfo.remark }}</el-descriptions-item>
      </el-descriptions>
      <el-table stripe style="width: 100%" border fit highlight-current-row :data="taskDetailData" :key="key">
        <el-table-column prop="student_id" align="center" label="学生ID" width="80" fixed></el-table-column>
        <el-table-column prop="username" align="center" label="姓名" width="100" fixed></el-table-column>
        <el-table-column prop="gradeName" align="center" label="年级" width="100" fixed></el-table-column>
        <el-table-column prop="subjectName" align="center" label="学科" width="100" fixed></el-table-column>
        <el-table-column prop="process" align="center" label="完成度" width="100" fixed></el-table-column>
        <el-table-column v-for="(day, index) in days" :key="index" :label="day" align="center" min-width="200">
          <template slot-scope="scope">
            <span v-if="scope.row[day]===1" style="color: #67C23A">已完成</span>
            <span v-else style="color: #F56C6C">未完成</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import objectable from "@/utils/objectable.js";
import dynamicTable from "@/components/DynamicTable/index";
import deleteDialog from "@/components/deleteDialog/index";
import tableMini from '@/utils/tableMini.js'
import permission from "@/directive/permission";
import {
  addStudentTask, delStudentTask,
  editStudentTask,
  queryStudentTask,
  searchSendOptions, showTaskDoneDetail
} from "@/api/teacher";
import {getAppChargeOptions, getBrowserWhiteUrl} from "@/api/appUpdate";

export default {
  mixins: [tableMini],
  components: {dynamicTable, deleteDialog},
  directives: {permission},
  data() {
    return {
      key: 1,
      colData: [], //动态控制table
      checkboxVal: ["ID", "任务对象", "对象选择", "任务类别", "学科", "任务名称", "任务描述", "是否提醒", "归属"],
      searchTable: "",
      select: "", //搜索条件
      tableData: [],
      listQuery: {
        startSize: 1,
        pageSize: 10,
        userId: localStorage.getItem("ID"),
      },
      addForm: {
        subject: '',
        name: '',
        app_charge_id: '',
        jump_type: '',
        send_type: '',
        send_id: '',
        date_type: '',
        date_select: '',
        expire_time: '',
        is_remind: -1,
        remind_time: '',
        remark: '',
        link_url: ''
      },
      formVisible: false,
      rules: {
        subject: [{required: true, message: '请选择学科', trigger: 'change'}],
        name: [{required: true, message: '请输入任务名称', trigger: 'blur'}],
        jump_type: [{required: true, message: '请选择跳转方式', trigger: 'change'}],
        send_type: [{required: true, message: '请选择任务对象', trigger: 'change'}],
        send_id: [{required: true, message: '请选择对象', trigger: 'change'}],
        date_type: [{required: true, message: '请选择任务类别', trigger: 'change'}],
      },
      editSubjects: false,
      deleteDialogs: {show: false, deleteText: '', deleteId: 0},
      options: [
        {value: 1, label: '语文'}, {value: 2, label: '数学'}, {value: 3, label: '英语'}, {
          value: 4,
          label: '政治'
        }, {value: 5, label: '历史'}, {value: 6, label: '地理'}, {value: 7, label: '物理'}, {
          value: 8,
          label: '化学'
        }, {value: 9, label: '生物'}, {value: 10, label: '科学'}
      ],
      paramOptions: [{label: 'StartArgs', value: 'StartArgs'}, {
        label: 'tiku_func_type',
        value: 'tiku_func_type'
      }, {label: 'isTopic', value: 'isTopic'}, {label: 'isYYGJ', value: 'isYYGJ'}, {label: 'url', value: 'url'}],
      sendOptions: [],
      appChargeOptions: [],
      pickerOptions: {
        disabledDate: (time) => {
          const todayEnd = new Date(); // 获取当前日期和时间
          const currentYear = todayEnd.getFullYear();
          const lastDayOfYear = new Date(currentYear, 11, 31, 23, 59, 59, 999); // 今年年末的最后一毫秒
          return time.getTime() < (todayEnd.getTime() - 24 * 3600 * 1000) || time.getTime() > lastDayOfYear.getTime();
        }
      },
      taskDetailVisible: false,
      taskDetailData: [],
      days: [],
      taskInfo: [],
      configOptions: [
        {label: '不跳转', value: 0},
        {label: '跳转到App', value: 1},
        {label: '跳转到音频', value: 2},
        {label: '跳转到视频', value: 3},
        {label: '跳转到网页', value: 5},
        {label: '跳转到图片', value: 6},
        {label: '跳转到文档', value: 7}
      ],
      whiteUrlOption:[]
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getStudentTaskControl()
    this.getAppChargeOptions()
    this.getWhiteUrlOptions()
  },
  methods: {
    Refresh() {
      this.listQuery = {startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
      this.getStudentTaskControl()
    },
    //搜索
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.agentName = this.searchTable
          this.getStudentTaskControl();
          break;
      }
    },
    openEdit(row) {
      this.getSendOptions(row.send_type)
      this.formVisible = true
      this.editSubjects = true
      this.addForm = {
        subject: row.subject,
        name: row.name,
        jump_type: row.jump_type,
        app_charge_id: row.app_charge_id,
        send_type: row.send_type,
        send_id: row.send_id,
        date_type: row.date_type,
        date_select: row.date_select,
        is_repeat: row.is_repeat,
        is_remind: row.is_remind,
        remind_time: row.remind_time,
        remark: row.remark,
        id: row.id,
        expire_time: row.expire_time,
        link_url: row.link_url
      }
    },
    editStudentTaskControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let editForm = JSON.parse(JSON.stringify(this.addForm))
          editForm.last_ip = sessionStorage.getItem("Ip")
          editForm.userId = localStorage.getItem("ID")
          editStudentTask(editForm).then(res => {
            this.$message.success(res.msg)
            this.getStudentTaskControl()
            this.formVisible = false
            this.editSubjects = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });
    },
    addStudentTaskControl(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.last_ip = sessionStorage.getItem("Ip")
          addForm.userId = localStorage.getItem("ID")
          addStudentTask(addForm).then(res => {
            this.$message.success(res.msg)
            this.getStudentTaskControl()
            this.formVisible = false
          }).catch(err => {
          })
        } else {
          return false;
        }
      });
    },
    getStudentTaskControl() {
      queryStudentTask(this.listQuery).then(res => {
        this.tableData = res.data
        this.total = res.total
      }).catch(err => {
        this.tableData = []
        this.total = 0
      })
    },
    delContent(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    showTaskDetail(id) {
      showTaskDoneDetail({
        taskId: id
      }).then(res => {
        this.taskDetailVisible = true
        this.taskDetailData = res.data['tableData']
        this.days = res.data['days']
        this.taskInfo = res.otherData
      })
    },
    //删除按钮事件
    deleteEvents() {
      let params = {
        userId: localStorage.getItem("ID"),
        last_ip: sessionStorage.getItem("Ip"),
        id: this.deleteDialogs.deleteId,
      }
      delStudentTask(params).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
        this.getStudentTaskControl()
      }).catch(err => {
        console.log("请求失败", err)
      })
    },
    //分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getStudentTaskControl()
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getStudentTaskControl()
    },
    //表格排序事件
    tableSortCge(column) {
      let order = ''
      column.order == "descending" ? order = 'desc' : order = 'asc'
      let sort = [{field: column.prop, sort: order}]
      this.listQuery.sort = JSON.stringify(sort)
      this.getStudentTaskControl()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.editSubjects = false
      this.$nextTick(() => {
        this.addForm = this.$options.data().addForm
        this.sendOptions = []
      })
    },
    getSendOptions(type) {
      this.addForm.send_id = ''
      searchSendOptions({
        userId: localStorage.getItem("ID"),
        type: type
      }).then(res => {
        this.sendOptions = res.data
      }).catch(err => {
        this.loading = false
        this.sendOptions = []
      })
    },
    getAppChargeOptions() {
      getAppChargeOptions({
        userId: localStorage.getItem("ID")
      }).then(res => {
        this.appChargeOptions = res.data
      }).catch(err => {
        this.appChargeOptions = []
      })
    },
    getWhiteUrlOptions() {
      getBrowserWhiteUrl({
        userId: localStorage.getItem("ID")
      }).then(res => {
        this.whiteUrlOption = res.data
      }).catch(err => {})
    }

  }
}
</script>

<style scoped>
.flex2 {
  display: -webkit-box; /* 老版本语法: Safari, iOS, Android browser, older WebKit browsers. */
  display: -moz-box; /* 老版本语法: Firefox (buggy) */
  display: -ms-flexbox; /* 混合版本语法: IE 10 */
  display: -webkit-flex; /* 新版本语法: Chrome 21+ */
  display: flex; /* 新版本语法: Opera 12.1, Firefox 22+ */
  -webkit-flex-wrap: nowrap;
  -ms-flex-wrap: nowrap;
  flex-wrap: nowrap;
}
</style>


